package com.example.wx.demo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Objects;

/**
 * @author sidian
 * @date 2021/4/7 18:26
 */
@Slf4j
@RestController
@RequestMapping("/wx")
public class WxController {
    private static final String TOKEN = "123456";
    private static final String APPID = "wx77798f1faa2ebfdd";
    private static final String SECRET = "54c9c9b316555777e4cef5acd0849d03";

    @GetMapping("/verify")
    public String verify(String signature, String timestamp, String nonce, String echostr) {
        // step 1
        LinkedList<String> array = CollUtil.newLinkedList(TOKEN, timestamp, nonce);
        array.sort(Comparator.naturalOrder());
        // step 2
        String sign = new Digester(DigestAlgorithm.SHA1).digestHex(String.join("", array));
        // step 3
        return Objects.equals(sign, signature) ? echostr : "";
    }

    @GetMapping("/user/info")
    public String getUserInfo(String code) {
        // access token
        String res = HttpUtil.get(String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                APPID, SECRET, code));
        Map<String, String> resMap = JSONUtil.toBean(res, new TypeReference<Map<String, String>>() {
        }, true);
        String accessToken = resMap.get("access_token");
        String openId = resMap.get("openid");
        // user info
        res = HttpUtil.get(String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId));
        resMap = JSONUtil.toBean(res, new TypeReference<Map<String, String>>() {
        }, true);
        return String.format(ResourceUtil.readUtf8Str("index.html"), resMap.get("nickname"), resMap.get("headimgurl"));
    }
}
